import random
import requests
import urllib3
from configs.settings import API_URL
from libraries.logger import log

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


class GoodsFilters(object):

    def __init__(self, cat_name, dress_type, page=1, limit=48):
        self.env = API_URL
        self.cat_name = cat_name
        self.dress_type = dress_type
        self.page = page
        self.limit = limit
        self.req = requests.Session()
        self.headers = {"Content-Type": "application/json", "x-app": 'h5', "x-token": "",
                        "x-project": "azazie", "x-countryCode": "US"}

    def __list_page_handler(self) -> dict:
        """列表页获取商品id/name/cat_id"""
        uri = f'1.0/list/content?cat_name={self.cat_name}&dress_type={self.dress_type}&page={self.page}&limit={self.limit}' \
              f'&sort_by=popularity'
        data = {"filters": {}, "is_plus_size": False, "in_stock": False, "from_style_quiz": False,
                "quiz_progress": "", "view_mode": []}
        response = self.req.post(self.env + uri, headers=self.headers, json=data, verify=False)
        if response.status_code != 200:
            return self.__list_page_handler()
        prod_list = response.json().get('data').get('prodList')
        goods_info = [
            {"goods_id": item.get('goodsId'), "goods_name": item.get("goodsName"), "cat_id": item.get("catId")}
            for item in prod_list
        ][0]
        return goods_info

    def __stock_goods_handler(self, goods_name, goods_id, cat_id) -> dict:
        """库存筛选，筛选出库存最大的第一个color/size组合"""
        uri = f'1.0/stock?goods_name={goods_name}&goods_id={goods_id}&dress_type={self.dress_type}&cat_id={cat_id}'
        response = self.req.get(self.env + uri, headers=self.headers, verify=False)
        if response.status_code != 200:
            return self.__stock_goods_handler(goods_name, goods_id, cat_id)
        if response.json().get('data').get('hasStock'):
            stock_number_map = response.json().get('data').get('stockNumberMap')
            stock_li = [{"map": key, "value": value} for key, value in stock_number_map.items()]
            first_item = sorted(stock_li, key=lambda i: i['value'], reverse=True)[0]
            try:
                first_stock_goods = {"color": first_item.get('map').split('*')[0],
                                     "size": first_item.get('map').split('*')[1],
                                     "num": first_item.get('value')}
                return first_stock_goods
            except Exception:
                first_stock_goods = {"color": first_item.get('map'),
                                     "size": None,
                                     "num": first_item.get('value')}
                return first_stock_goods

    def __detail_page_handler(self, goods_name, goods_id, color, size) -> dict:
        """通过color/size获取对应的id"""
        uri = f'1.0/product/first-screen?goods_name={goods_name}&goods_id={goods_id}&dress_type={self.dress_type}' \
              f'&goods_style_id=""&color=""'
        response = self.req.get(self.env + uri, headers=self.headers, verify=False)
        if response.status_code != 200:
            return self.__detail_page_handler(goods_name, goods_id, color, size)
        style_info = response.json().get('data').get('styleInfo')
        color_id = style_info.get('color').get(color).get('styleId')
        try:
            size_id = style_info.get('size').get(size).get('styleId')
        except Exception:
            size_id = None
        return {"color_id": color_id, "size_id": size_id}

    def __detail_page_non_batch_handler(self, goods_name, goods_id) -> dict:
        """非批量商品获取color_id/size_id"""
        uri = f'1.0/product/first-screen?goods_name={goods_name}&goods_id={goods_id}&dress_type={self.dress_type}' \
              f'&goods_style_id=""&color=""'
        response = self.req.get(self.env + uri, headers=self.headers, verify=False)
        if response.status_code != 200:
            return self.__detail_page_non_batch_handler(goods_name, goods_id)
        random_color = random.choice(
            [color for color in list(response.json().get('data').get('styleInfo').get('color').keys())]
        )
        random_size = random.choice(
            [size for size in list(response.json().get('data').get('styleInfo').get('size').keys())]
        )
        color_id = response.json().get('data').get('styleInfo').get('color').get(random_color).get('styleId')
        size_id = response.json().get('data').get('styleInfo').get('size').get(random_size).get('styleId')
        return {"color_id": color_id, "size_id": size_id}

    def _batch_goods_info_handler(self) -> dict:
        """批量商品"""
        goods_item = self.__list_page_handler()
        try:
            stock_res = self.__stock_goods_handler(goods_item.get('goods_name'), goods_item.get('goods_id'),
                                                   goods_item.get('cat_id'))
            detail_res = self.__detail_page_handler(
                goods_item.get('goods_name'), goods_item.get('goods_id'), stock_res.get('color'), stock_res.get('size')
            )
            final_goods_item = {"goods_name": goods_item.get('goods_name'), "goods_id": goods_item.get('goods_id'),
                                "cat_id": goods_item.get('cat_id'), "color_id": detail_res.get('color_id'),
                                "size_id": detail_res.get('size_id'), "stock_num": stock_res.get('num')}
            log.info(f"选取批量商品：{final_goods_item}")
        except Exception as exc:
            log.error(exc)
        else:
            return final_goods_item

    def _non_batch_goods_info_handler(self) -> dict:
        """非批量商品"""
        goods_item = self.__list_page_handler()
        try:
            detail_res = self.__detail_page_non_batch_handler(goods_item.get('goods_name'), goods_item.get('goods_id'))
            final_goods_item = {"goods_name": goods_item.get('goods_name'), "goods_id": goods_item.get('goods_id'),
                                "cat_id": goods_item.get('cat_id'), "color_id": detail_res.get('color_id'),
                                "size_id": detail_res.get('size_id'), "stock_num": None}
            log.info(f"选取非批量商品：{final_goods_item}")
        except Exception as exc:
            log.error(exc)
        else:
            return final_goods_item

    def goods_info_handler(self, non_batch=True) -> dict:
        return self._non_batch_goods_info_handler() if non_batch else self._batch_goods_info_handler()


if __name__ == '__main__':
    gf = GoodsFilters('swatches', 'dress')
    gf.goods_info_handler(non_batch=False)

"""
非批量：
bridesmaid-dresses 
wedding-dresses
mother-of-the-bride-dresses
批量：
dresses
groomsmen-accessories
swatches-fabric
"""
